# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

# 未来支付
APP_CONF = {
    '144': {  # 支付宝 50-5000 zs
        'API_KEY': 'c2e77f648551f9cb3f870b988a885b7a',
        'gateway': 'http://counter.futurepay.vip:8096/wpay/counter/deposit',
        'query_gateway': 'http://counter.futurepay.vip:8096/wpay/counter/orderQuery',
    },
    '146': {  # 支付宝 50-5000 witch
        'API_KEY': '847d6e064a06703318c5fe45d8852e0b',
        'gateway': 'http://counter.futurepay.vip:8096/wpay/counter/deposit',
        'query_gateway': 'http://counter.futurepay.vip:8096/wpay/counter/orderQuery',
    },
    '147': {  # 支付宝  50-5000 dwc
        'API_KEY': '1708ad597a85bd00c35eac45b0c11a34',
        'gateway': 'http://counter.futurepay.vip:8096/wpay/counter/deposit',
        'query_gateway': 'http://counter.futurepay.vip:8096/wpay/counter/orderQuery',
    },
    '148': {  # 支付宝 50-5000 loki
        'API_KEY': 'a9daf161178f6245e0c4cd0ea13e9ab9',
        'gateway': 'http://counter.futurepay.vip:8096/wpay/counter/deposit',
        'query_gateway': 'http://counter.futurepay.vip:8096/wpay/counter/orderQuery',
    },
    '149': {  # 支付宝 50-5000 TT
        'API_KEY': '6e097cd62fa20c82c622fd0ad393f030',
        'gateway': 'http://counter.futurepay.vip:8096/wpay/counter/deposit',
        'query_gateway': 'http://counter.futurepay.vip:8096/wpay/counter/orderQuery',
    },
    '150': {  # 支付宝 50-5000 TT
        'API_KEY': 'ecbf27aa23f30e45ce965bde16074b99',
        'gateway': 'http://counter.futurepay.vip:8096/wpay/counter/deposit',
        'query_gateway': 'http://counter.futurepay.vip:8096/wpay/counter/orderQuery',
    }
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'api_Key={}'.format(key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    """ 支付宝H5 1 """
    if service == 'alipay':
        return '1'
    return '1'


def _get_terminal_type(service):
    """
    1.mobile  
    2.pc 
    3.H5-mobile
    """
    if service == 'alipay':
        return '1'
    return '1'


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']
    parameter_dict = OrderedDict((
        ('timestamp', int(time.time())),
        ('terminal', _get_terminal_type(service)),
        ('api_version', '1.6'),
        ('notify_url', '{}/pay/api/{}/futurepay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('company_id', app_id),
        ('player_id', pay.user_id),
        ('company_order_id', str(pay.id)),
        ('amount_money', str(int(pay_amount))),
        ('channel_code', _get_pay_type(service)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    url = _get_gateway(app_id)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    _LOGGER.info("futurepay create: url: %s, %s", url, json.dumps(parameter_dict))
    response = requests.post(url, data=json.dumps(parameter_dict), headers=headers, timeout=5)
    _LOGGER.info("futurepay create: response: %s", response.text)
    return {'charge_info': json.loads(response.text)['data']['scalper_url']}


# OK
def check_notify_sign(request, app_id):
    data = json.loads(request.body)
    api_key = _get_api_key(app_id)
    _LOGGER.info("futurepay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['company_order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('futurepay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = 'success'
    trade_no = data['trade_no']
    total_fee = float(data['actual_amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 'success':
        _LOGGER.info('futurepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('company_id', app_id),
        ('company_order_no', str(pay_order.id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('futurepay query data, %s', json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=10)
    _LOGGER.info('futurepay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = data['data']['status']
        total_fee = float(pay_order.total_fee)
        trade_no = str(pay_order.third_id)
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        # 订单状态(1:处理成功，2：订单处理中, 3：订单失败)
        if trade_status == 1 and total_fee > 0:
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('futurepay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
